package com.edu.base.common.utils.javassist;

import java.util.Map;

import com.google.common.collect.Maps;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

public class JavassistUtils {
	public static void main(String[] args) throws ClassNotFoundException {
		test("1",1);
	}
 /**
  * 这个类和这个方法目前没用，本方法是获得某个方法所有参数的名字，实际我是想得到值，但是没找到解决方案
  * @param param1
  * @param param2
 * @throws ClassNotFoundException 
  */
	public static void test(String param1, int param2) throws ClassNotFoundException {
		Map<String,Object> params=getMethodParams();
		for (Map.Entry<String,Object> entry : params.entrySet()) { 
			Class c = Class.forName("java.lang.String");
			System.out.println(entry.getKey()); 
		}
		System.out.println(param1 + param2);
	}
    public static Map<String,Object> getMethodParams(){
    	Map<String,Object> result=Maps.newHashMap();
    	Class<?> clazz = JavassistUtils.class;
		ClassPool pool = ClassPool.getDefault();
		try {
			CtClass ctClass = pool.get(clazz.getName());
			CtMethod ctMethod = ctClass.getDeclaredMethod("test");
 
			// 使用javassist的反射方法的参数名
			MethodInfo methodInfo = ctMethod.getMethodInfo();
			CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
			LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
					.getAttribute(LocalVariableAttribute.tag);
			if (attr != null) {
				int len = ctMethod.getParameterTypes().length;
				// 非静态的成员函数的第一个参数是this
				int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
				System.out.print("test : ");
				for (int i = 0; i < len; i++) {
					result.put(attr.variableName(i + pos), attr.variableName(i + pos));
					System.out.print(attr.variableName(i + pos) + ' ');
				}
			}
		} catch (NotFoundException e) {
			e.printStackTrace();
		}

		return result;
    }
}
